using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Data;
using FlickrNet;

namespace PhotoBlender
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class FormMain : System.Windows.Forms.Form
	{
		private System.Windows.Forms.TextBox txtTag;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Button btnSearch;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.NumericUpDown numPhotos;
		private System.Windows.Forms.Panel panel1;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.TextBox txtLog;
		private System.Windows.Forms.Splitter splitter1;
		private System.Windows.Forms.ProgressBar pbarGet;
		private System.Windows.Forms.Button btnBlend;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.NumericUpDown numOpacity;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public FormMain()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			// set API key
			apikey = ConfigurationSettings.AppSettings["apikey"];
			filepath = ConfigurationSettings.AppSettings["filepath"];
			sbLog = new StringBuilder("Initializing...");
			files = new StringCollection();
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.txtTag = new System.Windows.Forms.TextBox();
			this.label1 = new System.Windows.Forms.Label();
			this.btnSearch = new System.Windows.Forms.Button();
			this.label2 = new System.Windows.Forms.Label();
			this.numPhotos = new System.Windows.Forms.NumericUpDown();
			this.panel1 = new System.Windows.Forms.Panel();
			this.pbarGet = new System.Windows.Forms.ProgressBar();
			this.txtLog = new System.Windows.Forms.TextBox();
			this.label3 = new System.Windows.Forms.Label();
			this.splitter1 = new System.Windows.Forms.Splitter();
			this.btnBlend = new System.Windows.Forms.Button();
			this.label4 = new System.Windows.Forms.Label();
			this.numOpacity = new System.Windows.Forms.NumericUpDown();
			((System.ComponentModel.ISupportInitialize)(this.numPhotos)).BeginInit();
			this.panel1.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.numOpacity)).BeginInit();
			this.SuspendLayout();
			// 
			// txtTag
			// 
			this.txtTag.Location = new System.Drawing.Point(40, 8);
			this.txtTag.Name = "txtTag";
			this.txtTag.Size = new System.Drawing.Size(200, 20);
			this.txtTag.TabIndex = 0;
			this.txtTag.Text = "";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(8, 8);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(32, 23);
			this.label1.TabIndex = 1;
			this.label1.Text = "Tags";
			this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// btnSearch
			// 
			this.btnSearch.Location = new System.Drawing.Point(184, 40);
			this.btnSearch.Name = "btnSearch";
			this.btnSearch.Size = new System.Drawing.Size(56, 24);
			this.btnSearch.TabIndex = 2;
			this.btnSearch.Text = "Search";
			this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
			// 
			// label2
			// 
			this.label2.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
			this.label2.Location = new System.Drawing.Point(8, 40);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(96, 23);
			this.label2.TabIndex = 4;
			this.label2.Text = "Number of photos";
			this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// numPhotos
			// 
			this.numPhotos.Location = new System.Drawing.Point(104, 40);
			this.numPhotos.Name = "numPhotos";
			this.numPhotos.Size = new System.Drawing.Size(64, 20);
			this.numPhotos.TabIndex = 5;
			// 
			// panel1
			// 
			this.panel1.Controls.Add(this.pbarGet);
			this.panel1.Controls.Add(this.txtLog);
			this.panel1.Controls.Add(this.label3);
			this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
			this.panel1.Location = new System.Drawing.Point(0, 132);
			this.panel1.Name = "panel1";
			this.panel1.Size = new System.Drawing.Size(258, 100);
			this.panel1.TabIndex = 6;
			// 
			// pbarGet
			// 
			this.pbarGet.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.pbarGet.Location = new System.Drawing.Point(0, 80);
			this.pbarGet.Name = "pbarGet";
			this.pbarGet.Size = new System.Drawing.Size(258, 23);
			this.pbarGet.TabIndex = 9;
			// 
			// txtLog
			// 
			this.txtLog.AcceptsReturn = true;
			this.txtLog.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.txtLog.Location = new System.Drawing.Point(0, 16);
			this.txtLog.Multiline = true;
			this.txtLog.Name = "txtLog";
			this.txtLog.ReadOnly = true;
			this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both;
			this.txtLog.Size = new System.Drawing.Size(258, 64);
			this.txtLog.TabIndex = 8;
			this.txtLog.Text = "";
			// 
			// label3
			// 
			this.label3.BackColor = System.Drawing.SystemColors.HotTrack;
			this.label3.Dock = System.Windows.Forms.DockStyle.Top;
			this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.label3.ForeColor = System.Drawing.SystemColors.ControlLightLight;
			this.label3.Location = new System.Drawing.Point(0, 0);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(258, 16);
			this.label3.TabIndex = 0;
			this.label3.Text = " Log";
			this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// splitter1
			// 
			this.splitter1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.splitter1.Dock = System.Windows.Forms.DockStyle.Bottom;
			this.splitter1.Location = new System.Drawing.Point(0, 129);
			this.splitter1.Name = "splitter1";
			this.splitter1.Size = new System.Drawing.Size(258, 3);
			this.splitter1.TabIndex = 7;
			this.splitter1.TabStop = false;
			// 
			// btnBlend
			// 
			this.btnBlend.Location = new System.Drawing.Point(184, 72);
			this.btnBlend.Name = "btnBlend";
			this.btnBlend.Size = new System.Drawing.Size(56, 23);
			this.btnBlend.TabIndex = 8;
			this.btnBlend.Text = "Blend";
			this.btnBlend.Click += new System.EventHandler(this.btnBlend_Click);
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(8, 72);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(96, 23);
			this.label4.TabIndex = 9;
			this.label4.Text = "Layer Opacity";
			this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// numOpacity
			// 
			this.numOpacity.DecimalPlaces = 1;
			this.numOpacity.Increment = new System.Decimal(new int[] {
																		 5,
																		 0,
																		 0,
																		 65536});
			this.numOpacity.Location = new System.Drawing.Point(104, 72);
			this.numOpacity.Minimum = new System.Decimal(new int[] {
																	   5,
																	   0,
																	   0,
																	   65536});
			this.numOpacity.Name = "numOpacity";
			this.numOpacity.Size = new System.Drawing.Size(64, 20);
			this.numOpacity.TabIndex = 10;
			this.numOpacity.Value = new System.Decimal(new int[] {
																	 1,
																	 0,
																	 0,
																	 0});
			// 
			// FormMain
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(258, 232);
			this.Controls.Add(this.numOpacity);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.btnBlend);
			this.Controls.Add(this.splitter1);
			this.Controls.Add(this.panel1);
			this.Controls.Add(this.numPhotos);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.btnSearch);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.txtTag);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
			this.Name = "FormMain";
			this.Text = "Form1";
			((System.ComponentModel.ISupportInitialize)(this.numPhotos)).EndInit();
			this.panel1.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.numOpacity)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new FormMain());
		}


		static readonly object _lock = new object();
		string tags;
		int count;
		string apikey;
		string filepath;
		int currentPhoto = 0;
		StringBuilder sbLog;
		StringCollection files;
		float opacity = 1.0f;

		private void btnSearch_Click(object sender, System.EventArgs e) {
			btnSearch.Enabled = false;

			// get retrieval values from form fields
			tags = this.txtTag.Text;
			count = (int)this.numPhotos.Value;

			// start thread to retrieve photos
			Thread t = new Thread(new ThreadStart(GetPhotos));
			t.Start();
		}

		/// <summary>
		/// Get the photos
		/// </summary>
		private void GetPhotos(){
			Flickr f = new Flickr(apikey);
			Photos photos = f.PhotosSearch(tags, TagMode.AllTags, "");
			
			// dont count over the number of photos found
			if(++count > photos.PhotoCollection.Count)
				count = photos.PhotoCollection.Count;

			// loop up to max photo count
			for(int i = 0; i < count; i++) {
				// get the photo
				RetrievePhoto(photos.PhotoCollection[i].MediumUrl);
				// set the current photo
				lock(_lock)
					currentPhoto = i;

				Invoke(new MethodInvoker(UpdateStatus));
				// Sleep a bit
				Thread.Sleep(50);
			}

			Invoke(new MethodInvoker(SearchComplete));
		}

		private void SearchComplete() {
			MessageBox.Show("Photo Download Complete.", "Download Complete", MessageBoxButtons.OK);
			this.pbarGet.Value = 0;
			btnSearch.Enabled = true;
		}

		private void UpdateStatus() {
			lock(_lock) {
				this.pbarGet.Value = (int)(((decimal)currentPhoto / (decimal)count) * 100);
				txtLog.Text = sbLog.ToString();
				txtLog.SelectionStart = txtLog.TextLength;
			}
		}

		/// <summary>
		/// Get photo from flickr and save it to disk
		/// </summary>
		/// <param name="url">Photo address</param>
		private void RetrievePhoto(string url){
			// get filename to save photo to
			string filename = string.Concat(filepath, GetFilename(url));
			
			// create web client to retrieve photo
			WebClient client = new WebClient();
			// get photo, save to file
			client.DownloadFile(url, filename);

			lock(_lock)
				sbLog.AppendFormat("\nDownloading: {0}", url);

			files.Add(filename);
		}

		/// <summary>
		/// Determine a filename from the url
		/// </summary>
		/// <param name="url">Photo Url</param>
		/// <returns>Photo Filename</returns>
		private string GetFilename(string url) {
			lock(_lock)
				return currentPhoto.ToString() + "photo.jpg";
		}

		private void btnBlend_Click(object sender, System.EventArgs e) {
			btnBlend.Enabled = false;
			opacity = (float)this.numOpacity.Value * 0.01f;
			Thread t = new Thread(new ThreadStart(BlendPhotos));
			t.Start();
		}

		private void BlendPhotos() {
			Blender  blender = new Blender(files);
			blender.BlendPhotos(opacity);

			Invoke(new MethodInvoker(BlendComplete));
		}

		private void BlendComplete()
		{
			MessageBox.Show("Blending Complete");
			btnBlend.Enabled = true;
		}
	}
}
